<template>
  <div>
    <el-drawer v-model="drawerVisible" :destroy-on-close="true" size="95%" :title="`${drawerProps.title}`">
      <div style="float: left; width: 70%; padding-right: 50px">
        <el-button type="primary" @click="handleSubmit" style="margin: auto"> 提交 </el-button>
        <SelectFilter :data="type_filter_data" :default-values="filterResult" @change="changeFilter" />
        <el-descriptions title="【题目说明】 📚" :column="1" border style="text-align: center"> </el-descriptions>
        <WangEditor v-model:value="content_description" height="270px" :editor-config="editorConfig" />
        <div v-for="index in content_answer.length" :key="index">
          <el-divider class="style-divider" content-position="left"></el-divider>
          <el-button type="primary" @click="deleteQuestion(index - 1)" style="margin: auto"> 删除该子题目 </el-button>
          <el-divider class="style-divider" content-position="left"></el-divider>
          <div v-if="filterResult.type != 'fillup'">
            {{ "【" + index + ". 题干】 📚 " }}
            <WangEditor v-model:value="content_stem[index - 1]" height="100px" />
          </div>
          {{ "【" + index + ". 试题分析】 📚" }}
          <WangEditor v-model:value="content_analysis[index - 1]" height="270px" />
          <div v-if="filterResult.type != 'fillup'">
            {{ "【" + index + ". 参考答案】 📚" }}
            <WangEditor v-model:value="content_answer[index - 1]" height="270px" />
          </div>
        </div>
        <el-button type="primary" @click="dialogVisible = true"> 内容预览 </el-button>
        <el-button type="primary" @click="addQuestion"> 新增子题目 </el-button>
        <el-button type="primary" @click="handleSubmit"> 提交 </el-button>
      </div>
      <!--      <div style="float: right; width: 30%">-->
      <!--        <el-descriptions title="【题目说明】 📚" :column="1" border></el-descriptions>-->
      <!--        <div class="view" v-html="content_description"></div>-->
      <!--        <div v-for="index in content_answer.length" :key="index">-->
      <!--          <el-descriptions :title="'【' + index + '. 题干】 📚 '" :column="1" border></el-descriptions>-->
      <!--          <div class="view" v-html="content_stem[index - 1]"></div>-->
      <!--          <el-descriptions :title="'【' + index + '. 试题分析】 📚'" :column="1" border></el-descriptions>-->
      <!--          <div class="view" v-html="content_analysis[index - 1]"></div>-->
      <!--          <el-descriptions :title="'【' + index + '. 参考答案】 📚'" :column="1" border></el-descriptions>-->
      <!--          <div class="view" v-html="content_answer[index - 1]"></div>-->
      <!--        </div>-->
      <!--      </div>-->
      <div style="float: right; width: 30%; padding-right: 50px">
        <div>
          <el-descriptions title="【所属章节】📚" :column="1" border style="text-align: center"> </el-descriptions>
          <TreeFilter
            ref="chapterTreeFilter"
            label="name"
            title="章节列表(单选)"
            :request-api="getChapterMenuApi"
            @change="changeTreeFilter"
            :api-params="drawerProps.course_id"
            :default-value="selected_chapter_id"
            :expand-on-click-node="true"
            :show-all-tag="false"
            :default-expand-all="false"
            style="width: 100%"
          />
        </div>
      </div>
      <el-dialog v-model="dialogVisible" title="富文本内容预览" width="1300px" top="50px" append-to-body>
        <div class="view" v-html="content_description"></div>
      </el-dialog>
    </el-drawer>
  </div>
</template>

<script setup lang="ts" name="editQuestionDrawer">
import { reactive, ref } from "vue";
import WangEditor from "@/components/WangEditor/index.vue";
import { ElMessage } from "element-plus";
import { getChapterMenuApi } from "@/api/modules/course";
import TreeFilter from "@/components/TreeFilter/index.vue";
import { IEditorConfig } from "@wangeditor/editor";
import SelectFilter from "@/components/SelectFilter/index.vue";
// import { addQuestion } from "@/api/modules/question";
// const rules = reactive({
//   avatar: [{ required: true, message: "请上传用户头像" }],
//   photo: [{ required: true, message: "请上传用户照片" }],
//   user_id: [{ required: true, message: "请填写用户id" }],
//   username: [{ required: true, message: "请填写用户姓名" }],
//   gender: [{ required: true, message: "请选择性别" }],
//   idCard: [{ required: true, message: "请填写身份证号" }],
//   email: [{ required: true, message: "请填写邮箱" }],
//   address: [{ required: true, message: "请填写居住地址" }]
// });

class AlertType {}

const editorConfig: IEditorConfig = {
  autoFocus: false,
  // eslint-disable-next-line @typescript-eslint/no-empty-function
  customAlert(info: string, type: AlertType): void {},
  readOnly: false,
  scroll: false,
  placeholder:
    "<p>如果是填空和选择题，请在挖空处采用“带有下划线的全角小括号对”，且把填空题的答案填写在小括号中，选择题不要写。<\p>" +
    "<p>如果想使用导出到word文档的功能，那么这里除了支持带有下划线的全角小括号对外，不支持其他任何格式（比如字体、字号、行高），但支持图片。</p>",
  MENU_CONF: {}
};

const drawerProps = ref<any>({
  isView: false,
  title: "",
  row: {}
});
let order_number = 0;
const chapterTreeFilter = ref<InstanceType<typeof TreeFilter>>();
const content_question_id = ref<string>("");
const content_bank_id = ref<string>("");
const content_description = ref("");
const content_stem = ref<string[]>([]);
const content_analysis = ref<string[]>([]);
const content_answer = ref<string[]>([]);
const dialogVisible = ref(false);
const drawerVisible = ref(false);

// 接收父组件传过来的参数
const acceptParams = (params: any) => {
  drawerProps.value = params;
  drawerVisible.value = true;
  order_number = params.order_number;

  filterResult.value.type = params.row.type || "";
  content_question_id.value = params.row.question_id ?? "";
  content_bank_id.value = params.bank_id ?? "";
  content_description.value = params.row.description ?? "";
  content_stem.value = JSON.parse(drawerProps.value.row.stem ?? "[]");
  content_analysis.value = JSON.parse(drawerProps.value.row.analysis ?? "[]");
  content_answer.value = JSON.parse(drawerProps.value.row.answer ?? "[]");

  selected_chapter_id.value = Number(params.chapter_id);
};

const addQuestion = async () => {
  // content_stem.value.length += 1;
  // content_analysis.value.length += 1;
  // content_answer.value.length += 1;

  content_stem.value.push("");
  content_analysis.value.push("");
  content_answer.value.push("");

  if (filterResult.value.type === "choice") {
    for (let index = 0; index < content_stem.value.length; ++index) {
      if (content_stem.value[index] === undefined || content_stem.value[index] === "") {
        content_stem.value[index] = "<p>A. &nbsp; &nbsp;B. &nbsp; &nbsp;C. &nbsp; &nbsp;D. &nbsp; &nbsp;</p>";
      }
    }
  }
};

const deleteQuestion = async (index: number) => {
  content_stem.value.splice(index, 1);
  content_analysis.value.splice(index, 1);
  content_answer.value.splice(index, 1);
};
const check_filleup_description = () => {
  let matched = content_description.value.match(/(?<=<u>).*?(?=<\/u>)/g);
  if (!matched) {
    ElMessage.error(`格式错误！`);
    return false;
  }
  return true;
};

const generate_fillup_answer = () => {
  if (content_stem.value.length == 0) {
    addQuestion();
  }

  let matched = content_description.value.match(/(?<=<u>（).*?(?=）<\/u>)/g) || [];
  let answer = "";
  for (let match of matched) {
    answer += "<p>" + match + "</p>";
  }
  content_answer.value[0] = answer;
  return true;
};

const set_stem = (content: string) => {
  for (let index = 0; index < content_stem.value.length; ++index) {
    if (content_stem.value[index] === undefined || content_stem.value[index] === "") {
      content_stem.value[index] = content;
    }
  }
};

// 提交数据（新增/编辑）
const handleSubmit = async () => {
  try {
    if (content_description.value == "") {
      ElMessage.error(`请填写题目说明！`);
      return false;
    }
    if (content_stem.value[0].match(/^A\..*?B\..*?C\..*?D\..*?$/g)) {
      if (filterResult.value.type == "") {
        filterResult.value.type = "choice";
      }
    }
    if (filterResult.value.type === "") {
      ElMessage.error(`请选择题目类型！`);
      return false;
    }

    if (filterResult.value.type == "choice") {
      for (let answer of content_answer.value) {
        if (!answer.match(/(?<=<p>)[A-Z]+(?=<\/p>)/g)) {
          ElMessage.error(`选择题的选项中只能出现大写字母`);
          return false;
        }
      }
    }
    // 对于填空题的处理
    if (filterResult.value.type === "fillup") {
      if (!check_filleup_description()) {
        return false;
      }
      if (!generate_fillup_answer()) {
        ElMessage.error(`请把答案直接写在【题目说明】里。`);
        return false;
      }
    }
    const questionInfo = reactive<any>({
      question_id: content_question_id.value,
      bank_id: content_bank_id.value,
      description: content_description.value,
      stem: JSON.stringify(content_stem.value),
      analysis: JSON.stringify(content_analysis.value),
      answer: JSON.stringify(content_answer.value),
      order_number: order_number,
      chapter_id: selected_chapter_id.value,
      course_id: drawerProps.value.course_id,
      type: filterResult.value.type,
      count: content_stem.value.length
    });
    const data = await drawerProps.value.api!({ ...questionInfo });
    if (data.code !== "") {
      ElMessage.error(data.msg);
      return;
    }
    ElMessage.success({ message: `提交成功！` });
    drawerProps.value.getTableList!();
    drawerVisible.value = false;
  } catch (error) {
    console.log(error);
  }
  return true;
};
const selected_chapter_id = ref<number>(0);
const changeTreeFilter = (val: string) => {
  ElMessage.success(`你选择了 id 为 ${val} 的数据🤔`);
  selected_chapter_id.value = Number(val);
};
const type_filter_data = [
  {
    title: "题目类型",
    key: "type",
    options: [
      {
        label: "选择题",
        value: "choice",
        icon: "ShoppingCart"
      },
      {
        label: "填空题",
        value: "fillup",
        icon: "Van"
      },
      {
        label: "问答题",
        value: "answer",
        icon: "Van"
      }
    ]
  }
];
const filterResult = ref({ type: "" });
const changeFilter = (val: typeof filterResult.value) => {
  filterResult.value = val;
  if (filterResult.value.type === "choice") {
    set_stem("<p>A. &nbsp; &nbsp;B. &nbsp; &nbsp;C. &nbsp; &nbsp;D. &nbsp; &nbsp;</p>");
  } else if (filterResult.value.type === "fillup") {
    set_stem("");
    generate_fillup_answer();
  }
};
defineExpose({
  acceptParams
});
</script>
<style scoped lang="scss">
@import "questionEditor";
</style>
